<template>
    <div>
        <el-card class="box-card">
            <el-form :inline="true" :model="queryData" class="demo-form-inline" label-width="100px">
                <el-form-item label="客户名称">
                    <el-input v-model="queryData.clientName" placeholder="客户名称" size="small"></el-input>
                </el-form-item>
                <el-form-item label="所属员工">
                    <el-input v-model="queryData.empName" placeholder="员工名称" size="small"></el-input>
                </el-form-item>
                <el-form-item label="添加日期">
                    <el-date-picker
                            size="small"
                            v-model="queryData.joinTime"
                            type="daterange"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="添加渠道">
                    <el-select v-model="queryData.clientSource" clearable placeholder="添加渠道" size="small">
                        <el-option v-for="item in dictionary.clientSource" :key="item.value" :label="item.label" :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="性别">
                    <el-select v-model="queryData.clientSex" clearable placeholder="性别" size="small">
                        <el-option label="男" value="1"></el-option>
                        <el-option label="女" value="0"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="流失状态">
                    <el-select v-model="queryData.clientType" clearable placeholder="流失状态" size="small">
                        <el-option v-for="item in dictionary.clientType" :key="item.value" :label="item.label"
                                   :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item size="large">
                    <el-button type="primary" @click="queryDataHandle(1, 10)" size="small">查询</el-button>
<!--                    <el-divider direction="vertical"></el-divider>-->
                    <el-button type="primary" @click="resetQuery" size="small">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <div class="interspaceH"></div>

        <el-card class="box-card">
            <div style="display:flex;justify-content: space-between">
                <div>
                    <div style="font-size: 12px">
                        共{{ dataSource.length }}个客户
                    </div>
                    <div style="font-size: 12px">已选择{{ multipleSelection.length }}个客户</div>
                    <div class="interspaceH"></div>
                </div>
                <div>
                    <el-button plain size="small" @click="multipleSelection.length > 0 ? updateRateVisible = true : $message.error('未选择客户');">批量修改评分</el-button>
<!--                    <el-divider direction="vertical"></el-divider>-->
                    <el-button plain size="small" @click="multipleSelection.length > 0 ? updateTagsVisible = true : $message.error('未选择客户');$refs.setClientsTags.resetData()">批量打标签</el-button>
<!--                    <el-divider direction="vertical"></el-divider>-->
                    <el-button type="primary" size="small" @click="exportClientHandle">导出excel</el-button>
                </div>
            </div>

            <el-table :data="dataSource" @selection-change="rowChange"
                      :header-cell-style="{background:'#F3F4F7',color:'#555'}" style="width: 100%">
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column prop="clientName" label="客户名称" :formatter="formatter"></el-table-column>
                <el-table-column prop="empName" label="所属员工" :formatter="formatter"></el-table-column>
                <el-table-column label="企业标签" width="400">
                    <template slot-scope="scope">
                        <el-tag :key="index" v-for="(tag, index) in scope.row.tagList" style="margin: 0 10px 10px 0">
                            {{ tag.clientTagsName }}
                        </el-tag>
                        <div v-if="scope.row.tagList == null || scope.row.tagList.length == 0">
                            --
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="joinTime" label="添加日期" :formatter="formatter"></el-table-column>
                <el-table-column prop="clientSource" label="渠道" :formatter="formatter"></el-table-column>
                <el-table-column prop="clientSex" label="性别" :formatter="formatter"></el-table-column>
                <el-table-column prop="clientRate" label="客户评分" :formatter="formatter"></el-table-column>
                <el-table-column label="流失状态">
                    <template slot-scope="scope">
                        <span v-if="scope.row.clientType == 1" style="color: #00cc19">正常</span>
                        <span v-if="scope.row.clientType == 2" style="color: #f88e2d">流失客户</span>
                        <span v-if="scope.row.clientType == 3" style="color: #006dcc">客户公海</span>
                        <span v-if="scope.row.clientType == -1" style="color: crimson">黑名单</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button @click="detailHandle(scope.row)" type="text" size="small">详情</el-button>
                        <el-button @click="clientHandle(scope.row, 'seas')" type="text" size="small">投入公海</el-button>
                        <el-button @click="clientHandle(scope.row, 'blacklist')" type="text" size="small">投入黑名单</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <div class="interspaceH"></div>

            <el-pagination @size-change="queryDataHandle(pagePagination.currentPage,$event)"
                           @current-change="queryDataHandle($event,pagePagination.pageSize)"
                           :current-page="pagePagination.currentPage"
                           :page-sizes="pagePagination.pageSizes" :page-size="pagePagination.pageSize"
                           layout="total, sizes, prev, pager, next"
                           :total="pagePagination.total">
            </el-pagination>
        </el-card>

        <el-dialog title="批量修改评分" :visible.sync="updateRateVisible" width="30%">
            <UpdateRate ref="setClientRate" :clientNum="multipleSelection.length"/>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="setCustomersRate" size="small">确定</el-button>
                <el-button @click="updateRateVisible = false" size="small">返回</el-button>
            </span>
        </el-dialog>

        <el-dialog title="批量打标签" :visible.sync="updateTagsVisible" width="40%">
            <UpdateClientsTags ref="setClientsTags" :clientNum="multipleSelection.length"/>
            <span slot="footer" class="dialog-footer">
                <el-button @click="setCustomersTags" type="primary" size="small">设置</el-button>
                <el-button @click="updateTagsVisible = false;" size="small">返回</el-button>
            </span>
        </el-dialog>

        <ClientDetail ref="clientDetail"/>
    </div>
</template>

<script>
const queryData = {
    clientName: '',//客户名称
    empName: '',//所属员工
    joinTime: '',//添加日期
    clientSource: '',//渠道
    clientSex: '',//性别
    clientType: ''//流失状态
}

//多选框 - 开始
const clientSource = [
    {
        value: '0',
        label: '手机添加'
    },
    {
        value: '1',
        label: '活动添加'
    }
]

const clientType = [
    {
        value: '-1',
        label: '黑名单'
    },
    {
        value: '1',
        label: '正常'
    },
    {
        value: '2',
        label: '流失客户'
    },
    {
        value: '3',
        label: '客户公海'
    }
]

const clientSex = [
    {
        value: '1',
        label: '男'
    },
    {
        value: '0',
        label: '女'
    }
]
//多选框 - 结束

import ClientDetail from '@/views/customer/client/client_detail'
import UpdateRate from '@/views/customer/client/client_update_rate'
import UpdateClientsTags from "@/views/customer/client/client_update_tags"

export default {
    name: "ClientAttributeList",
    components:{
        ClientDetail,
        UpdateRate,
        UpdateClientsTags
    },
    data() {
        return {
            updateRateVisible: false,
            updateTagsVisible: false,
            multipleSelection: [],
            tablePage: 0,
            dictionary: {
                clientSource: clientSource,
                clientType: clientType,
                clientSex: clientSex
            },
            fieldType: {
                clientSex: "array",
                clientSource: "array",
                clientType: "array",
                joinTime: "datetime"
            },
            queryData: {...queryData},
            dataSource: [],
            pagePagination: {
                currentPage: 1,
                pageSizes: [10, 15, 20, 25],
                pageSize: 10,
                total: 0
            }
        }
    },
    mounted() {
        this.queryDataHandle()
    },
    methods: {
        queryDataHandle(page = 1, row = 10) {
            let that = this;
            let queryData = {...that.queryData}

            if (queryData.joinTime != null && queryData.joinTime != "") {
                queryData['startJoinTime'] = queryData.joinTime[0]
                queryData['endJoinTime'] = queryData.joinTime[1]
                delete queryData.joinTime
            }

            let payload = {
                ...queryData,
                sortField: "c.join_time",
                pageNum: page,
                pageSize: row
            }
            that.$request("/api/customers/getCustomersByParams/1_0", payload, "POST").then((data) => {
                that.dataSource = data.rows
                that.pagePagination['total'] = data.total
                that.pagePagination['pageSize'] = data.row
            })
        },
        resetQuery() {
            this.queryData = {...queryData}
        },
        rowChange(val) {
            this.multipleSelection = val;
        },
        formatter(row, column) {
            let field = column.property;
            return this.$utils.formatterForLable(field, row[field], this.fieldType, this['dictionary'][field]);
        },
        detailHandle(row) {
            this.$refs.clientDetail.open(true, row)
        },
        setCustomersTags() {
            let newTag = this.$refs.setClientsTags.getData()
            let newUnionTag = []

            newTag.map((item) => {
                newUnionTag.push(item.tagId)
            })

            this.multipleSelection.map((item) => {
                if (item.unionTag == null) {
                    item['unionTag'] = newTag
                } else {
                    let newUnionTag = JSON.parse(item['unionTag']).concat(newTag);
                    item['unionTag'] = newUnionTag
                }
                delete item['tagList']
                item['unionTag'] = JSON.stringify(item['unionTag'])


                item['newUnionTag'] = JSON.stringify(newUnionTag)
            })

            let payload = {
                clientList:this.multipleSelection
            }

            this.$request("/api/tags/setCustomersTags/1_0", payload, "POST").then((data) => {
                if (data.data.state == "error") {
                    this.$message.error(data.data.msg)
                } else {
                    this.$message.success(data.data.msg)
                }
                this.updateTagsVisible = false
                this.queryDataHandle()
            })
        },
        setCustomersRate() {
            let rateData = this.$refs.setClientRate.getData()

            this.multipleSelection.map((item) => {
                if (item['clientRate'] == null) {
                    item['clientRate'] = 0
                }

                if (rateData.clientRateType == '1') {
                    item['clientRate'] += rateData.clientRate
                } else if (rateData.clientRateType == '2'){
                    item['clientRate'] -= rateData.clientRate
                }
                item['clientRate'] = item['clientRate'].toString()

                item['clientRateRemark'] = rateData.clientRateRemark
            })

            let payload = {
                clientList: this.multipleSelection,
                clientHistoryRemark: "修改了评分"
            }

            this.$request("/api/customers/updateCustomers/1_0", payload, "POST").then((data) => {
                this.$message({type: 'success',message: '修改评分成功'})
                this.$refs.setClientRate.resetData()
                this.queryDataHandle()
                this.updateRateVisible = false;
            })
        },
        exportClientHandle() {
            this.$requestFile("/api/customers/exportCustomers/1_0", {sortField: "c.join_time"}, "客户信息.xlsx")
        },
        clientHandle(data, type) {
            let that = this

            if (type == "seas") {
                that.$confirm('是否投入至公海客户?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let payload = {
                        clientId: data.clientId,
                        empId: data.empId,
                        clientType: '3',
                        clientIsFriend: "false",
                        clientHistoryRemark: that.$store.getters.getUserInfo.userNickname + "将客户投入至公海客户"
                    }

                    that.$request("/api/customers/updateCustomer/1_0", payload, "POST").then((data) => {
                        that.$message.success("将客户投入至公海客户成功！")
                        that.queryDataHandle();
                    })
                })
            } else if (type == "blacklist") {
                that.$prompt('原因？', '是否投入至黑名单', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(({ value }) => {
                    let payload = {
                        clientId: data.clientId,
                        clientType: '-1',
                        clientIsFriend: "false",
                        operator: that.$store.getters.getUserInfo.userNickname,
                        operationTime: this.$moment(),
                        blackCause: value,
                        clientHistoryRemark: that.$store.getters.getUserInfo.userNickname + "将客户投入至黑名单"
                    }

                    that.$request("/api/customers/updateCustomer/1_0", payload, "POST").then((data) => {
                        that.$message.success("将客户投入至黑名单成功！")
                        that.queryDataHandle();
                    })
                })
            }
        }
    }
}
</script>

<style scoped>
.box-card .el-input {
    width: 200px;
}

.box-card .el-select {
    width: 200px;
}
</style>
